package cn.tedu._08article.controller;

import cn.tedu._08article.base.response.JsonResult;
import cn.tedu._08article.base.response.StatusCode;
import cn.tedu._08article.mapper.ArticleMapper;
import cn.tedu._08article.mapper.UserMapper;
import cn.tedu._08article.pojo.dto.ArticleAddParam;
import cn.tedu._08article.pojo.dto.UserLoginParam;
import cn.tedu._08article.pojo.entity.Article;
import cn.tedu._08article.pojo.vo.ArticleVO;
import cn.tedu._08article.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Validated
@RestController
@Slf4j
@Tag(name = "API文档")
@RequestMapping("/v1/user/")
public class UserArticleController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @PostMapping("login")
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 10)
    public JsonResult loginUser(@RequestBody UserLoginParam param, HttpSession session){
        log.debug("登录参数:"+param);
        UserVO loginVO=userMapper.selectUserByUsernameAndPassword(param);
        if (loginVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",loginVO);
        return JsonResult.OK(loginVO);
    }
    @PostMapping("add")
    @Operation(summary = "发表文章")
    @ApiOperationSupport(order = 10)
    public JsonResult addArticle(@RequestBody @Validated ArticleAddParam param, HttpSession session){
        log.debug("输入参数："+param);
        UserVO loginVO=(UserVO) session.getAttribute("user");
//        if (loginVO==null){
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
        Article article=new Article();
        BeanUtils.copyProperties(param,article);
        article.setUserId(loginVO.getId());
        articleMapper.insertArticle(article);
        return JsonResult.OK();
    }

    @GetMapping("/select/{id}")
    @Operation(summary = "查询文章")
    @ApiOperationSupport(order = 20)
    public JsonResult selectById(@PathVariable @Range(min=1L,max=100L,message="文章id需要在1-100之间") Long id){
        log.debug("输入参数："+id);
        List<ArticleVO> artilceVO=articleMapper.selectArticleById(id);
        return JsonResult.OK(artilceVO);
    }


}
